<template>
  <view class="content">
    <u-navbar title="产品管理" :border="false" :autoBack="true"></u-navbar>
    
    <!-- 操作工具栏 -->
    <view class="toolbar">
      <view class="search-container">
        <u-search v-model="searchKey" placeholder="请输入产品名称" @search="search" @custom="search"></u-search>
        <u-dropdown class="dropdown" ref="uDropdown">
          <u-dropdown-item v-model="categoryId" title="选择分类" :options="categoryOptions"></u-dropdown-item>
        </u-dropdown>
      </view>
      <view class="action-container">
        <u-button type="primary" text="新增产品" icon="plus" size="mini" @click="goToEdit()"></u-button>
        <u-button type="info" text="分类管理" icon="list" size="mini" @click="goToCategory"></u-button>
      </view>
    </view>
    
    <!-- 产品列表 -->
    <view class="product-list">
      <u-empty v-if="productList.length === 0" text="暂无产品数据"></u-empty>
      <view v-else class="list-content">
        <view v-for="(item, index) in productList" :key="item.id" class="product-item">
          <view class="product-image">
            <image :src="item.image || '/static/default-product.png'" mode="aspectFill"></image>
          </view>
          <view class="product-info">
            <view class="product-name">{{ item.name }}</view>
            <view class="product-price">¥{{ item.price || '0.00' }}</view>
            <view class="product-category">分类：{{ item.categoryName || '未分类' }}</view>
            <view class="product-code" v-if="item.code">编号：{{ item.code }}</view>
          </view>
          <view class="product-actions">
            <u-button type="primary" text="编辑" size="mini" @click="goToEdit(item)"></u-button>
            <u-button :type="item.statue ? 'warning' : 'success'" :text="item.statue ? '禁用' : '启用'" size="mini" @click="toggleStatus(item)"></u-button>
            <u-button type="error" text="删除" size="mini" @click="confirmDelete(item)"></u-button>
          </view>
        </view>
      </view>
      
      <!-- 分页 -->
      <view class="pagination">
        <u-loadmore :status="loadMoreStatus" :load-text="loadText" @loadmore="loadMore" />
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKey: '',
      categoryId: null,
      categoryOptions: [],
      productList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loadMoreStatus: 'loadmore',
      loadText: {
        loadmore: '点击或上拉加载更多',
        loading: '正在加载...',
        nomore: '没有更多了'
      }
    }
  },
  computed: {
    hasMore() {
      return this.productList.length < this.total;
    }
  },
  onLoad() {
    this.fetchCategoryOptions();
    this.fetchProducts();
  },
  onPullDownRefresh() {
    this.refresh();
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 500);
  },
  onReachBottom() {
    if (this.hasMore) {
      this.loadMore();
    }
  },
  methods: {
    // 获取分类选项
    fetchCategoryOptions() {
      this.$api.get('/api/Category/Tree')
        .then(res => {
          if (res.data.code === 200) {
            let options = [{ value: null, label: '全部分类' }];
            
            res.data.data.forEach(category => {
              options.push({
                value: category.id,
                label: category.name
              });
              
              if (category.children && category.children.length > 0) {
                category.children.forEach(child => {
                  options.push({
                    value: child.id,
                    label: `　${child.name}`
                  });
                });
              }
            });
            
            this.categoryOptions = options;
          }
        })
        .catch(err => {
          console.error(err);
        });
    },
    
    // 获取产品列表
    fetchProducts() {
      uni.showLoading({
        title: '加载中'
      });
      
      const params = {
        key: this.searchKey,
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        categoryId: this.categoryId
      };
      
      this.$api.get('/api/Product', params)
        .then(res => {
          if (res.data.code === 200) {
            // 如果是第一页，直接赋值；否则追加数据
            if (this.currentPage === 1) {
              this.productList = res.data.data.items || [];
            } else {
              this.productList = [...this.productList, ...(res.data.data.items || [])];
            }
            
            this.total = res.data.data.total || 0;
            
            // 更新加载更多状态
            this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore';
          } else {
            this.$u.toast(res.data.msg || '获取产品列表失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 搜索产品
    search() {
      this.currentPage = 1;
      this.fetchProducts();
    },
    
    // 加载更多
    loadMore() {
      if (this.loadMoreStatus === 'loading') return;
      
      this.loadMoreStatus = 'loading';
      this.currentPage += 1;
      this.fetchProducts();
    },
    
    // 刷新数据
    refresh() {
      this.currentPage = 1;
      this.fetchProducts();
    },
    
    // 切换产品状态
    toggleStatus(product) {
      const action = product.statue ? 'disable' : 'enable';
      const actionText = product.statue ? '禁用' : '启用';
      
      uni.showLoading({
        title: `${actionText}中`
      });
      
      this.$api.put(`/api/Product/${product.id}/${action}`)
        .then(res => {
          if (res.data.code === 200) {
            this.$u.toast(`${actionText}成功`);
            // 更新本地状态
            product.statue = !product.statue;
          } else {
            this.$u.toast(res.data.msg || `${actionText}失败`);
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 确认删除
    confirmDelete(product) {
      uni.showModal({
        title: '提示',
        content: `确定要删除"${product.name}"吗？`,
        success: res => {
          if (res.confirm) {
            this.deleteProduct(product.id);
          }
        }
      });
    },
    
    // 删除产品
    deleteProduct(productId) {
      uni.showLoading({
        title: '删除中'
      });
      
      this.$api.delete(`/api/Product/${productId}`)
        .then(res => {
          if (res.data.code === 200) {
            this.$u.toast('删除成功');
            // 从列表中移除
            this.productList = this.productList.filter(item => item.id !== productId);
          } else {
            this.$u.toast(res.data.msg || '删除失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 跳转到编辑页面
    goToEdit(product) {
      let url = '/pages/product/edit';
      if (product) {
        url += `?id=${product.id}`;
      }
      uni.navigateTo({
        url
      });
    },
    
    // 跳转到分类管理页面
    goToCategory() {
      uni.navigateTo({
        url: '/pages/product/category'
      });
    }
  }
}
</script>

<style lang="scss">
.content {
  padding: 20rpx;
  
  .toolbar {
    margin-bottom: 20rpx;
    
    .search-container {
      display: flex;
      margin-bottom: 20rpx;
      
      .u-search {
        flex: 1;
        margin-right: 20rpx;
      }
      
      .dropdown {
        width: 200rpx;
      }
    }
    
    .action-container {
      display: flex;
      justify-content: flex-end;
      
      .u-button {
        margin-left: 20rpx;
      }
    }
  }
  
  .product-list {
    .list-content {
      .product-item {
        display: flex;
        background-color: #ffffff;
        border-radius: 12rpx;
        padding: 20rpx;
        margin-bottom: 20rpx;
        
        .product-image {
          width: 160rpx;
          height: 160rpx;
          margin-right: 20rpx;
          
          image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
        }
        
        .product-info {
          flex: 1;
          
          .product-name {
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          
          .product-price {
            font-size: 28rpx;
            color: #ff6600;
            margin-bottom: 10rpx;
          }
          
          .product-category, .product-code {
            font-size: 24rpx;
            color: #666;
            margin-bottom: 6rpx;
          }
        }
        
        .product-actions {
          display: flex;
          flex-direction: column;
          justify-content: center;
          
          .u-button {
            margin-bottom: 10rpx;
          }
        }
      }
    }
    
    .pagination {
      margin-top: 20rpx;
      margin-bottom: 30rpx;
    }
  }
}
</style> 